﻿@using System.Web.Script.Serialization;
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="~/Scripts/highcharts.js"></script>
<script src="~/Scripts/exporting.js"></script>
@*<script>
        var modelObj = JSON.parse('@Html.Raw(new JavaScriptSerializer().Serialize(Model))')
    </script>*@
<section class="container reports">
    <div class="page-heading col-lg-12 col-md-12 col-xs-12 clear-padding" style="overflow:hidden">
        <div class="pull-left col-lg-8 col-md-4 col-xs-12"><h1><span>Reports</span><span id="doctorName"></span></h1></div>

    </div>
    <form class="form-horizontal" role="form">

        <div class="form-group">
            <label class="control-label reportType pull-left">Report Type</label>
            <div class="col-lg-5">
                <label class="radio-inline"> <input type="radio" name="reportType" id="patientLocationReport" value="patient" checked> Patient Location </label>
                <label class="radio-inline"> <input type="radio" name="reportType" id="financeReport" value="finance"> Finance </label>
            </div>
        </div>
    </form>
    <form class="form-horizontal">
        <div class="control-group">
            <label class="control-label pull-left">Start Date</label>
            <div class="col-lg-2">
                <input type="text" id="startDate" class="form-control datepicker" placeholder="Start Date(dd/MM/yyyy)" value="@DateTime.Today.AddDays(-60).ToString("dd'/'MM'/'yyyy")" />
            </div>
        </div>
        <div class="control-group">
            <label class="control-label pull-left">End Date</label>
            <div class="col-lg-2">
                <input type="text" id="endDate" class="datepicker form-control" placeholder="End Date(dd/MM/yyyy)" value="@DateTime.Today.ToString("dd'/'MM'/'yyyy")" />
            </div>
        </div>
        <div class="control-group">
            <div class="col-lg-2">
                <select id="location" class="form-control" style="color: black;">
                    <option id="" value="0">(Select Location)</option>
                </select>
            </div>
        </div>
        <div class="control-group">
            <div class="col-lg-2">
                <select id="doctors" class="form-control" style="color: black;">
                    <option id="" value="0">(Select Doctor)</option>
                </select>
            </div>
        </div>
        <div class="control-group">
            <div>
                <button type="button" id="search" class="btn btn-primary">Search</button>
            </div>
        </div>
    </form>
    <div id="resultViewer" class="invisible">
        <div id="container"></div>
        <div class="invisible">
            <table id="dataLocationTable" class="table table-striped table-bordered">
                <thead style="background-color: rgb(124, 124, 194);">
                    <tr>
                        <th>Name</th>
                        <th>Location</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>
        <div class="invisible">
            <table id="dataFinanceTable" class="table table-striped table-bordered">
                <thead style="background-color: rgb(124, 124, 194);">
                    <tr>
                        <th>Date</th>
                        <th>Name</th>
                        <th>Paid</th>
                        <th>Balance</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>
        <button id="export" class="btn btn-primary">Export to csv</button>
    </div>
    <div id="noResultFound" class="invisible">
        No Result found.
    </div>
</section>
<script type="text/javascript">

    var dynaPatientLocationtable = $('#dataLocationTable').dynatable({
        dataset: {
            records: []
        }
    }).data('dynatable');
    var dynaFinancetable = $('#dataFinanceTable').dynatable({
        dataset: {
            records: []
        }
    }).data('dynatable');
    var jsonData = [];
    $(document).ready(function () {
        LoadLocation();
        $("#location").on("change", function () {
            $('#doctors').val('').attr('selected', true);
            $('#doctors').trigger("change");
            $.ajax({
                type: "POST",
                url: _AbsolutePath + 'Appointment/GetDoctorList',
                contentType: "application/json",
                data: JSON.stringify({ LocId: $("#location").val() }),
                caller: arguments.callee.name,//gets currently running function name
                dataType: "json", //Cross domain call (even json also work)
                success: function (res) {
                    $('#doctors').empty();
                    //if (res.length > 1)
                    $('#doctors').append($('<option id=""\/>').val('0').text('(Select Doctor)'));
                    for (var i = 0; i < res.length; i++) {
                        $('#doctors').append($('<option id="' + res[i].Id + '"\/>').val(res[i].Id).text(res[i].Detail));
                    }
                    //if (res.length == 1) {
                    //    $('#doctors option#' + res[0].Id).prop("selected", true);
                    //    $('#doctors').trigger("change");
                    //}
                },
                error: function (xhr) { debugger; }
            });
        });
        $('input[name=reportType]:checked').change(function () {
            $("#resultViewer").addClass("invisible");
        });
        $("#search").click(function () {
            var startDate, endDate;
            var inputStartDate = $("#startDate").val();
            var inputEndDate = $("#endDate").val();
            if (environment == "prod") {
                startDate = inputStartDate.split('/')[1] + "/" + inputStartDate.split('/')[0] + "/" + inputStartDate.split('/')[2];
                endDate = inputEndDate.split('/')[1] + "/" + inputEndDate.split('/')[0] + "/" + inputEndDate.split('/')[2];
            } else {
                startDate = inputStartDate.split('/')[0] + "/" + inputStartDate.split('/')[1] + "/" + inputStartDate.split('/')[2];
                endDate = inputEndDate.split('/')[0] + "/" + inputEndDate.split('/')[1] + "/" + inputEndDate.split('/')[2];
            }
            if ($('input[name=reportType]:checked').val() == "finance") {
                
                $.ajax({
                    type: "POST",
                    url: _AbsolutePath + 'Report/GetFinanceReport',
                    contentType: "application/json",
                    data: JSON.stringify({ startDate: startDate, endDate: endDate, locId: $("#location option:selected").val(), docId: $("#doctors option:selected").val() }),
                    caller: arguments.callee.name,//gets currently running function name
                    dataType: "json", //Cross domain call (even json also work)
                    success: function (res) {
                        ProcessFinanceResult(res);
                    },
                    error: function (xhr) { }
                });
            } else {
                $.ajax({
                    type: "POST",
                    url: _AbsolutePath + 'Report/LocationBasedReport',
                    contentType: "application/json",
                    data: JSON.stringify({ startDate: startDate, endDate: endDate, locId: $("#location option:selected").val(), docId: $("#doctors option:selected").val() }),
                    caller: arguments.callee.name,//gets currently running function name
                    dataType: "json", //Cross domain call (even json also work)
                    success: function (res) {
                        ProcessPatientLocationResult(res);
                    },
                    error: function (xhr) { debugger; }
                });
            }
        });
        $('#export').click(function () {
            //var data = jsonData;
            if (!jsonData.length)
                return;
            JSONToCSVConvertor(jsonData, "Report", true);
        });
    });

    function loadChart(modelObj, desc) {
        //var data = [];
        //_.each(modelObj, function (item) {
        //    data.push([item.Detail, item.Id])
        //});
        $('#container').highcharts({
            title: {
                text: desc.chartName,
                x: -20 //center
            },
            series: [{
                type: 'pie',
                name: desc.recordName,
                data: modelObj
            }],
            credits: { enabled: false }
        });
    }

    function LoadLocation() {
        $.ajax({
            type: "POST",
            url: _AbsolutePath + 'Appointment/GetLocationList',
            contentType: "application/json",
            dataType: "json", //Cross domain call (even json also work)
            data: JSON.stringify({ clinicCode: localStorage.getItem("ClinicCode") }),
            success: function (res) {
                for (var i = 0; i < res.length; i++) {
                    $('#location').append($('<option id="' + res[i].Id + '"\/>').val(res[i].Id).text(res[i].Detail));
                }
            },
            error: function (xhr) { }
        });
    }
    function ProcessPatientLocationResult(res) {
        var data = [];
        _.each(res[1].Value, function (item) {
            data.push({ name: item.Patient_Name, location: item.Patient_Location_Name })
        });
        if (data.length) {
            $("#resultViewer").removeClass("invisible");
            $("#dataLocationTable").parent().removeClass("invisible");
            $("#noResultFound").addClass("invisible");
            $("#dataFinanceTable").parent().addClass("invisible");
        } else {
            $("#resultViewer").addClass("invisible");
            $("#noResultFound").removeClass("invisible");
        }

        var chartData = [];
        _.each(res[0].Value, function (item) {
            chartData.push([item.Patient_Location_Name, item.PatientCount])
        });

        loadChart(chartData, {chartName : "Patient's Location Report", recordName : "Patient"});
       

        dynaPatientLocationtable.settings.dataset.originalRecords = data;
        dynaPatientLocationtable.process();
        jsonData = data;
        
    }

    function ProcessFinanceResult(res) {
        var data = [];
        _.each(res[1].Value, function (item) {
            data.push({ date: item._Appt_Date, name: item.Patient_Name, paid: item.Amt_Paid, balance: item.Balance })
        });
        if (data.length) {
            $("#resultViewer").removeClass("invisible");
            $("#dataFinanceTable").parent().removeClass("invisible");
            $("#noResultFound").addClass("invisible");
            $("#dataLocationTable").parent().addClass("invisible");
        } else {
            $("#resultViewer").addClass("invisible");
            $("#noResultFound").removeClass("invisible");
        }

        var chartData = [];
        _.each(res[0].Value, function (item) {
            chartData.push([item.Date, item.AmtPaid])
        });
        
        loadChart(chartData, {chartName : "Finance Report", recordName : "Income"});
       
        dynaFinancetable.settings.dataset.originalRecords = data;
        dynaFinancetable.process();
        jsonData = data;

    }

    function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) {
        //If JSONData is not an object then JSON.parse will parse the JSON string in an Object
        var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;

        var CSV = '';
        //Set Report title in first row or line

        CSV += ReportTitle + '\r\n\n';

        //This condition will generate the Label/Header
        if (ShowLabel) {
            var row = "";

            //This loop will extract the label from 1st index of on array
            for (var index in arrData[0]) {

                //Now convert each value to string and comma-seprated
                row += index + ',';
            }

            row = row.slice(0, -1);

            //append Label row with line break
            CSV += row + '\r\n';
        }

        //1st loop is to extract each row
        for (var i = 0; i < arrData.length; i++) {
            var row = "";

            //2nd loop will extract each column and convert it in string comma-seprated
            for (var index in arrData[i]) {
                row += '"' + arrData[i][index] + '",';
            }

            row.slice(0, row.length - 1);

            //add a line break after each row
            CSV += row + '\r\n';
        }

        if (CSV == '') {
            alert("Invalid data");
            return;
        }

        //Generate a file name
        var fileName = "MyReport_";
        //this will remove the blank-spaces from the title and replace it with an underscore
        fileName += ReportTitle.replace(/ /g, "_");

        //Initialize file format you want csv or xls
        var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);

        // Now the little tricky part.
        // you can use either>> window.open(uri);
        // but this will not work in some browsers
        // or you will not get the correct file extension    

        //this trick will generate a temp <a /> tag
        var link = document.createElement("a");
        link.href = uri;

        //set the visibility hidden so it will not effect on your web-layout
        link.style = "visibility:hidden";
        link.download = fileName + ".csv";

        //this part will append the anchor tag and remove it after automatic click
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
</script>
